package com.shwread.android.ui.widget;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.graphics.drawable.shapes.Shape;
import android.os.Build;
import android.text.Html;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.NewActionHelp;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw.activity.BaseBusinessActivity;
import com.shwread.android.qysw.activity.MainActivity;
import com.shwread.android.qysw.activity.QyFeedBackActivity;
import com.shwread.android.qysw10000243.R;
import com.shwread.android.ui.page.NewEnterprisePage;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.httpsdk.constant.ResultCode;
import com.shwread.httpsdk.http.base.AbstractHttpPostDracom;
import com.shwread.httpsdk.http.callback.ActionListener;
import com.shwread.httpsdk.http.callback.BaseAction;
import com.shwread.httpsdk.util.Util;

import org.apache.http.Header;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import logic.bean.RegionModuleBean;
import logic.constants.AppConfig;
import logic.constants.Const;


/**
 * 企业专区的栏目视图
 *
 * @author zouqp
 *         2015-01-19
 */

public class RegionModelView extends LinearLayout implements OnClickListener {
    public static final int PAGESIZE = 30;
    public static final int CONTENT_ITEM_MAX_SIZE = 60;
    // total list items, used to detect is at the bottom of listview.
    private Context mContext;                                                  //
    List<RegionModuleBean> mModuleList = new ArrayList<>(); //模块列表
    private LinearLayout ll_group1, ll_group2, ll_group3;
    private TextView tv_module1, tv_module2, tv_module3, tv_module4, tv_module5, tv_module6;
    private OnModuleSelectedListener onSelectedListener;
    private int selectedIndex = -1;                                            //一个不会用到的初始值
    private TextView selectedText;
    private BaseBusinessActivity baseActivity;
    private RelativeLayout rl_blank_content;
    LinearLayout containerView;
    private boolean canSwitchModule = true;

    private RegionModuleAction moduleAction = null;

    /**
     * @param context
     */
    public RegionModelView(Context context) {
        super(context);
        initWithContext(context);
    }

    public RegionModelView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initWithContext(context);
    }

    public RegionModelView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initWithContext(context);
    }

    private void initWithContext(Context context) {
        mContext = context;
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
        containerView = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.region_module_layout, null);
        ll_group1 = (LinearLayout) containerView.findViewById(R.id.ll_group1);
        ll_group2 = (LinearLayout) containerView.findViewById(R.id.ll_group2);
        ll_group3 = (LinearLayout) containerView.findViewById(R.id.ll_group3);
        rl_blank_content = (RelativeLayout) containerView.findViewById(R.id.rl_blank_content);

        tv_module1 = (TextView) containerView.findViewById(R.id.tv_module1);
        tv_module2 = (TextView) containerView.findViewById(R.id.tv_module2);
        tv_module3 = (TextView) containerView.findViewById(R.id.tv_module3);
        tv_module4 = (TextView) containerView.findViewById(R.id.tv_module4);
        tv_module5 = (TextView) containerView.findViewById(R.id.tv_module5);
        tv_module6 = (TextView) containerView.findViewById(R.id.tv_module6);

        tv_module1.setOnClickListener(this);
        tv_module2.setOnClickListener(this);
        tv_module3.setOnClickListener(this);
        tv_module4.setOnClickListener(this);
        tv_module5.setOnClickListener(this);
        tv_module6.setOnClickListener(this);
        addView(containerView, lp);
        //getModules( );
    }

    public void setOnModuleSelectedListener(OnModuleSelectedListener listener) {
        onSelectedListener = listener;
    }

    public void setBaseActivity(BaseBusinessActivity baseActivity) {
        this.baseActivity = baseActivity;
    }

    public void setCanSwitchModule(boolean canSwitchModule) {
        this.canSwitchModule = canSwitchModule;
    }

    @Override
    public void onClick(View v) {
        switchModule(v);
    }

    /******************************
     * 一些私有的方法
     *****************************************/

    private void showBlankView(boolean isShow) {
        if (isShow) {
            rl_blank_content.setVisibility(View.VISIBLE);
        } else {
            rl_blank_content.setVisibility(View.GONE);
        }
    }

    private void refreshModuleUI() {
        baseActivity.getUIHandler().post(new Runnable() {
            @Override
            public void run() {
                if (mModuleList == null || mModuleList.size() == 0) {
                    //通知 外部的调用者， 没有模块数据。
                    showBlankView(true);
                    if (onSelectedListener != null) {
                        onSelectedListener.onError("没有模块数据");
                    }
                    return;
                }
                initModuleViews();
                switchModule(tv_module1);
            }
        });
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void switchModule(View v) {
        TextView textView = (TextView) v;
        if (textView == null) {
            return;
        }
        Object id = textView.getTag();
        if (id == null) {
            return;
        }
        long moduleId = (Long) id;
        int currentIndex = -1;
        //找到点击的那个模块
        for (int i = 0; i < mModuleList.size(); i++) {
            RegionModuleBean Module = mModuleList.get(i);
            if (moduleId == Module.getModuleId()) {
                if ("2".equals(Module.getModuleType())) {
                    if (Module.getSubModuleName() != null && Module.getSubTargetValus() != null) {
                        String moduleTypeValue = Module.getModuleTypeValue();
                        String moduleName = Module.getModuleName();
                        String subModuleName = Module.getSubModuleName();
                        String subTargetValus = Module.getSubTargetValus();
                        Intent intent = new Intent(mContext, QyFeedBackActivity.class);
                        intent.putExtra("moduleTypeValue", moduleTypeValue);
                        intent.putExtra("subTargetValus", subTargetValus);
                        intent.putExtra("moduleName", moduleName);
                        intent.putExtra("subModuleName", subModuleName);
                        intent.putExtra("moduleId", moduleId);
                        mContext.startActivity(intent);
                        return;
                    }
                }
                currentIndex = i;
                break;
            }
        }
        if (currentIndex == -1) {
            return; //没有找到，所以返回
        }

        if (currentIndex == selectedIndex) {
            return; //点击了原来选中的模块， 直接返回
        }

        if (canSwitchModule) {
            canSwitchModule = true;
        } else {
            return;
        }

        //将原来的模块设回为未选中
        ShapeDrawable itemBg;
        if (selectedText != null) {
            itemBg = getModuleItemBgDrawable(mModuleList.get(selectedIndex).getModuleColor(), 1);
            selectedText.setBackground(itemBg);
            selectedText.setTextColor(0xffffffff); //设为白色
            selectedText.setText(mModuleList.get(selectedIndex).getModuleName());
        }

        selectedIndex = currentIndex;
        selectedText = textView;
        //设置当前的模块为选中
        itemBg = getModuleItemBgDrawable(mModuleList.get(selectedIndex).getModuleColor(), 2);
        selectedText.setBackground(itemBg);
        selectedText.setTextColor(mModuleList.get(selectedIndex).getModuleColor()); //设为下发的颜色
        String ModuleName = mModuleList.get(selectedIndex).getModuleName();
        selectedText.setText(Html.fromHtml("<u>" + ModuleName + "</u>"));

        //调用 外部的监听函数
        if (onSelectedListener != null) {
            onSelectedListener.moduleSelected(mModuleList.get(selectedIndex).getModuleId());
        }
    }

    public void getModules() {
        //todo , 调用真实的接口， 获取模块数据
        //mModuleList = RegionModuleBean.generateFakeModule(5);
        getModuleDatas();
    }

    /****************************** 一些私有的方法 *************************************/
    private void getModuleDatas() {
//        moduleAction = new RegionModuleAction(mContext, new ModuleActionListener());
//        moduleAction.start();
        NewActionHelp.qryModuleList(mContext,0,new ObjectHttpResponseHandler<List<RegionModuleBean>>() {
            @Override
            public void onFailure(int result, Header[] headers, String s, Throwable throwable) {
                Log.e("111111", "qryModuleList" + s);
                final String errMsg = ResultCode.getResultText(result);
                baseActivity.getUIHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        showBlankView(true);
                        if (onSelectedListener != null) {
                            onSelectedListener.onError(errMsg);
                        }
                    }
                });
            }

            @Override
            public void onSuccess(int i, Header[] headers, List<RegionModuleBean> regionModuleBeanList, String s) {
                Log.e("1111112", "qryModuleList" + s);
                NewEnterprisePage.netAvilible = true;
                mModuleList = regionModuleBeanList;
                refreshModuleUI();
            }

            @Override
            public Type getType() {
                return new TypeToken<List<RegionModuleBean>>() {
                }.getType();
            }
        });
    }

    private void checkModuleItemBackGroundColor() {
        if (mModuleList == null || mModuleList.size() == 0) {
            return;
        }
        for (int i = 0; i < mModuleList.size(); i++) {
            RegionModuleBean module = mModuleList.get(i);
            if (Util.isEmpty(module.getModuleBackgroundColor())) {
                module.setModuleBackgroundColor("ff3ba5de");
            }
        }
    }

    /**
     * 获取背景drawable
     *
     * @param color
     * @param flag  1为填充背景， 2为描边
     * @return
     */
    private ShapeDrawable getModuleItemBgDrawable(int color, int flag) {
        int radius = 8;
        float[] outerR = new float[]{
                radius,
                radius,
                radius,
                radius,
                radius,
                radius,
                radius,
                radius
        };
        RoundRectShape roundRectShape = new RoundRectShape(outerR, null, outerR);
        ShapeDrawable shapeDrawable = new ShapeDrawable(roundRectShape); // 组合圆角矩形和ShapeDrawable
        shapeDrawable.getPaint().setFlags(Paint.ANTI_ALIAS_FLAG);//抗锯齿
        shapeDrawable.getPaint().setColor(color); // 设置形状的颜色
        if (flag == 1) {
            shapeDrawable.getPaint().setStyle(Paint.Style.FILL);
        } else {
            shapeDrawable.getPaint().setStyle(Paint.Style.STROKE);
            shapeDrawable.getPaint().setStrokeWidth(1);
        }
        return shapeDrawable;
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void initModuleViews() {
        if (mModuleList == null || mModuleList.size() == 0) return;
        int count = mModuleList.size();
        checkModuleItemBackGroundColor();
        RegionModuleBean module;
        ShapeDrawable itemBg;
        switch (count) {
            case 1:
                ll_group1.setVisibility(View.VISIBLE);
                ll_group2.setVisibility(View.GONE);
                ll_group3.setVisibility(View.GONE);

                tv_module1.setVisibility(View.VISIBLE);
                module = mModuleList.get(0);
                tv_module1.setText(module.getModuleName());
                itemBg = getModuleItemBgDrawable(module.getModuleColor(), 1);
                tv_module1.setBackground(itemBg);
                tv_module1.setTag(module.getModuleId());

                tv_module2.setVisibility(View.GONE);
                tv_module3.setVisibility(View.GONE);
                tv_module4.setVisibility(View.GONE);
                tv_module5.setVisibility(View.GONE);
                tv_module6.setVisibility(View.GONE);
                containerView.setVisibility(View.GONE);
                break;
            case 2:
                ll_group1.setVisibility(View.VISIBLE);
                ll_group2.setVisibility(View.VISIBLE);
                ll_group3.setVisibility(View.GONE);

                tv_module1.setVisibility(View.VISIBLE);
                tv_module2.setVisibility(View.VISIBLE);

                module = mModuleList.get(0);
                tv_module1.setText(module.getModuleName());
                itemBg = getModuleItemBgDrawable(module.getModuleColor(), 1);
                tv_module1.setBackground(itemBg);
                tv_module1.setTag(module.getModuleId());

                module = mModuleList.get(1);
                tv_module2.setText(module.getModuleName());
                itemBg = getModuleItemBgDrawable(module.getModuleColor(), 1);
                tv_module2.setBackground(itemBg);
                tv_module2.setTag(module.getModuleId());

                tv_module3.setVisibility(View.GONE);
                tv_module4.setVisibility(View.GONE);
                tv_module5.setVisibility(View.GONE);
                tv_module6.setVisibility(View.GONE);

                break;
            case 3:
                ll_group1.setVisibility(View.VISIBLE);
                ll_group2.setVisibility(View.VISIBLE);
                ll_group3.setVisibility(View.VISIBLE);

                tv_module1.setVisibility(View.VISIBLE);
                tv_module2.setVisibility(View.VISIBLE);
                tv_module3.setVisibility(View.VISIBLE);

                module = mModuleList.get(0);
                tv_module1.setText(module.getModuleName());
                itemBg = getModuleItemBgDrawable(module.getModuleColor(), 1);
                tv_module1.setBackground(itemBg);
                tv_module1.setTag(module.getModuleId());

                module = mModuleList.get(1);
                tv_module2.setText(module.getModuleName());
                itemBg = getModuleItemBgDrawable(module.getModuleColor(), 1);
                tv_module2.setBackground(itemBg);
                tv_module2.setTag(module.getModuleId());

                module = mModuleList.get(2);
                tv_module3.setText(module.getModuleName());
                itemBg = getModuleItemBgDrawable(module.getModuleColor(), 1);
                tv_module3.setBackground(itemBg);
                tv_module3.setTag(module.getModuleId());

                tv_module4.setVisibility(View.GONE);
                tv_module5.setVisibility(View.GONE);
                tv_module6.setVisibility(View.GONE);

                break;
            case 4:
                ll_group1.setVisibility(View.VISIBLE);
                ll_group2.setVisibility(View.VISIBLE);
                ll_group3.setVisibility(View.GONE);

                tv_module1.setVisibility(View.VISIBLE);
                tv_module2.setVisibility(View.VISIBLE);
                tv_module3.setVisibility(View.GONE);
                tv_module4.setVisibility(View.VISIBLE);
                tv_module5.setVisibility(View.VISIBLE);
                tv_module6.setVisibility(View.GONE);

                module = mModuleList.get(0);
                tv_module1.setText(module.getModuleName());
                itemBg = getModuleItemBgDrawable(module.getModuleColor(), 1);
                tv_module1.setBackground(itemBg);
                tv_module1.setTag(module.getModuleId());

                module = mModuleList.get(1);
                tv_module2.setText(module.getModuleName());
                itemBg = getModuleItemBgDrawable(module.getModuleColor(), 1);
                tv_module2.setBackground(itemBg);
                tv_module2.setTag(module.getModuleId());

                module = mModuleList.get(2);
                tv_module4.setText(module.getModuleName());
                itemBg = getModuleItemBgDrawable(module.getModuleColor(), 1);
                tv_module4.setBackground(itemBg);
                tv_module4.setTag(module.getModuleId());

                module = mModuleList.get(3);
                tv_module5.setText(module.getModuleName());
                itemBg = getModuleItemBgDrawable(module.getModuleColor(), 1);
                tv_module5.setBackground(itemBg);
                tv_module5.setTag(module.getModuleId());

                break;
            case 5:
                ll_group1.setVisibility(View.VISIBLE);
                ll_group2.setVisibility(View.VISIBLE);
                ll_group3.setVisibility(View.VISIBLE);

                tv_module1.setVisibility(View.VISIBLE);
                tv_module2.setVisibility(View.VISIBLE);
                tv_module3.setVisibility(View.VISIBLE);
                tv_module4.setVisibility(View.GONE);
                tv_module5.setVisibility(View.VISIBLE);
                tv_module6.setVisibility(View.VISIBLE);

                module = mModuleList.get(0);
                tv_module1.setText(module.getModuleName());
                itemBg = getModuleItemBgDrawable(module.getModuleColor(), 1);
                tv_module1.setBackground(itemBg);
                tv_module1.setTag(module.getModuleId());

                module = mModuleList.get(1);
                tv_module2.setText(module.getModuleName());
                itemBg = getModuleItemBgDrawable(module.getModuleColor(), 1);
                tv_module2.setBackground(itemBg);
                tv_module2.setTag(module.getModuleId());

                module = mModuleList.get(2);
                tv_module3.setText(module.getModuleName());
                itemBg = getModuleItemBgDrawable(module.getModuleColor(), 1);
                tv_module3.setBackground(itemBg);
                tv_module3.setTag(module.getModuleId());

                module = mModuleList.get(3);
                tv_module5.setText(module.getModuleName());
                itemBg = getModuleItemBgDrawable(module.getModuleColor(), 1);
                tv_module5.setBackground(itemBg);
                tv_module5.setTag(module.getModuleId());

                module = mModuleList.get(4);
                tv_module6.setText(module.getModuleName());
                itemBg = getModuleItemBgDrawable(module.getModuleColor(), 1);
                tv_module6.setBackground(itemBg);
                tv_module6.setTag(module.getModuleId());

                ViewGroup.LayoutParams layoutparams = tv_module1.getLayoutParams();
                layoutparams.height = 2 * layoutparams.height;
                tv_module1.setLayoutParams(layoutparams);

                break;
            case 6:
            default:
                ll_group1.setVisibility(View.VISIBLE);
                ll_group2.setVisibility(View.VISIBLE);
                ll_group3.setVisibility(View.VISIBLE);

                tv_module1.setVisibility(View.VISIBLE);
                tv_module2.setVisibility(View.VISIBLE);
                tv_module3.setVisibility(View.VISIBLE);
                tv_module4.setVisibility(View.VISIBLE);
                tv_module5.setVisibility(View.VISIBLE);
                tv_module6.setVisibility(View.VISIBLE);

                module = mModuleList.get(0);
                tv_module1.setText(module.getModuleName());
                itemBg = getModuleItemBgDrawable(module.getModuleColor(), 1);
                tv_module1.setBackground(itemBg);
                tv_module1.setTag(module.getModuleId());

                module = mModuleList.get(1);
                tv_module2.setText(module.getModuleName());
                itemBg = getModuleItemBgDrawable(module.getModuleColor(), 1);
                tv_module2.setBackground(itemBg);
                tv_module2.setTag(module.getModuleId());

                module = mModuleList.get(2);
                tv_module3.setText(module.getModuleName());
                itemBg = getModuleItemBgDrawable(module.getModuleColor(), 1);
                tv_module3.setBackground(itemBg);
                tv_module3.setTag(module.getModuleId());

                module = mModuleList.get(3);
                tv_module4.setText(module.getModuleName());
                itemBg = getModuleItemBgDrawable(module.getModuleColor(), 1);
                tv_module4.setBackground(itemBg);
                tv_module4.setTag(module.getModuleId());

                module = mModuleList.get(4);
                tv_module5.setText(module.getModuleName());
                itemBg = getModuleItemBgDrawable(module.getModuleColor(), 1);
                tv_module5.setBackground(itemBg);
                tv_module5.setTag(module.getModuleId());

                module = mModuleList.get(5);
                tv_module6.setText(module.getModuleName());
                itemBg = getModuleItemBgDrawable(module.getModuleColor(), 1);
                tv_module6.setBackground(itemBg);
                tv_module6.setTag(module.getModuleId());
                break;
        }
    }

    /**
     * 获取专区模块的action 类
     */
    public class RegionModuleAction extends AbstractHttpPostDracom {
        RegionModuleAction(Context context, ActionListener actionListener) {
            super(context, "qryModuleList.do", actionListener);
        }

        @Override
        public void getParameter(HashMap<String, String> parameter_map) {
            parameter_map.put("account", Const.phone_number);
            parameter_map.put("enterpriseId", AppConfig.getEnterpriseId());
            parameter_map.put("timeStamp", String.valueOf(timeStamp));
            parameter_map.put("cid", cid(Const.phone_number + Const.ACCOUNTTYPE + Const.CLIENTTYPE + timeStamp + AppConfig.getEnterpriseId()));
        }

        @Override
        public void doResponseXml(String xml) {
            println(xml);
            int result;
            try {
                JSONObject jsonObject = new JSONObject(xml);
                result = jsonObject.getInt("resultCode");
                if (result == 1000) {
                    List<RegionModuleBean> modules;
                    Gson gson = new Gson();
                    modules = gson.fromJson(jsonObject.getString("returnObject"), new TypeToken<List<RegionModuleBean>>() {
                    }.getType());
                    listener.OK(modules);
                } else {
                    listener.ERROR(result, ResultCode.getResultText(result));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        protected void doRequestHeader(HashMap<String, String> header_map) {

        }

        @Override
        public void dispose() {

        }
    }

    /**
     * 获取企业专区模块的 action listener
     */
    private class ModuleActionListener extends BaseAction {
        @SuppressWarnings("unchecked")
        @Override
        public void OK(Object obj) {
            NewEnterprisePage.netAvilible = true;
            mModuleList = (List<RegionModuleBean>) obj;
            refreshModuleUI();
            moduleAction.stop();
            moduleAction = null;
        }

        @Override
        public void ERROR(int resultCode, String message) {
            super.onError();
            //通知 外部的调用者， 出错了。

            final String errMsg = message;
            baseActivity.getUIHandler().post(new Runnable() {
                @Override
                public void run() {
                    showBlankView(true);
                    if (onSelectedListener != null) {
                        onSelectedListener.onError(errMsg);
                    }
                }
            });
            moduleAction.stop();
            moduleAction = null;
        }
    }

    private static class MyShapeDrawable extends ShapeDrawable {
        //Paint.ANTI_ALIAS_FLAG代表这个画笔的图形是光滑的
        private Paint mStrokePaint = new Paint(Paint.ANTI_ALIAS_FLAG);

        public MyShapeDrawable(Shape s) {
            super(s);
            mStrokePaint.setStyle(Paint.Style.STROKE);
        }

        public void setStrokeColor(int color) {
            mStrokePaint.setColor(color);
        }

        public void setStrokeWidth(float width) {
            mStrokePaint.setStrokeWidth(width);
        }

        @Override
        protected void onDraw(Shape s, Canvas c, Paint p) {
            //绘制填充效果的图形
            s.draw(c, p);
            //绘制边框
            s.draw(c, mStrokePaint);
        }
    }

    public interface OnModuleSelectedListener {
        void moduleSelected(long ModuleId);

        void onError(String error);
    }
}
